package utils;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
	public static Map<String, String> getDataMap(String json) {
		Map<String, String> map = new HashMap<String, String>();
		JSONObject jsonObject = JSONObject.fromObject(json);
		String status = "";
		String submitStatus = "";
		String errMsg = "";
		JSONArray messages = null;
		if (jsonObject.containsKey("status")) {
			status = jsonObject.getString("status");
		}
		if (jsonObject.containsKey("messages")) {
			messages = jsonObject.getJSONArray("messages");
		}
		if (jsonObject.containsKey("data")) {
			Object data = jsonObject.get("data");
			if (data instanceof JSONObject) {
				JSONObject dataJson = (JSONObject) data;
				if (dataJson.containsKey("errMsg")) {
					errMsg = dataJson.getString("errMsg");
				}
				if (dataJson.containsKey("submitStatus")) {
					submitStatus = dataJson.getString("submitStatus");
				}
			}
		}
		map.put("status", status);
		map.put("messages", messages.join(","));
		map.put("errMsg", errMsg);
		map.put("submitStatus", submitStatus);
		return map;
	}

	public static String getVarFromJs(String js, String varName) {
		int start = js.indexOf(varName);
		String subContent = js.substring(start);
		subContent = subContent.substring(subContent.indexOf("["), subContent
				.indexOf(";"));
		return subContent;
	}

	public static void main(String args[]) {
		String json = "{\"validateMessagesShowId\":\"_validatorMessage\",\"status\":true,\"httpstatus\":200,\"data\":{\"submitStatus\":true},\"messages\":[],\"validateMessages\":{}}";
		Map<?, ?> map = getDataMap(json);
		System.out.println(map);
	}
}
